package com.liu.project.service.impl;

import com.liu.project.pojo.LoginUser;
import com.liu.project.pojo.SysRole;
import com.liu.project.pojo.User;

import com.liu.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: project
 * @description:
 * @author: 86187
 * @create: 2022-01-31 15:33
 **/
@Transactional
@Service
@Slf4j
public class AuthService  implements  UserDetailsService{

    @Autowired
    UserService userService;
/*
* 将用户名或者qq作为账号进行登录
*
*
* */
    @Override
    //username是用户名或者qq账号
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        User users = userService.findUserByUserName(username);
        User userByEmail = userService.findUserByEmail(username);
        System.out.println(users==null && userByEmail==null);
        if (users==null && userByEmail==null) throw new InternalAuthenticationServiceException("用户不存在");//账号和email都不存在
        if (users!=null){
            String role = users.getRole();
            SysRole sysRole = new SysRole(role);
            List<SysRole> authorities = new ArrayList<>();
            authorities.add(sysRole);

            System.out.println("authService==>"+authorities);

            LoginUser loginUser = new LoginUser();
            loginUser.setId(users.getId());
            loginUser.setUsername(users.getUsername());
            loginUser.setPassword(users.getPassword());
            loginUser.setAuthorities(authorities);

            log.info("用户验证通过==》"+username);
            return loginUser;
        }
        return null;

    }





}
